/**
 * 
 */
package com.airnewslinkosky.ticket.ui.order;

import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.OrderInfoResult;
import com.airnewslinkosky.ticket.model.SearchOrder;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.ui.Main;
import com.airnewslinkosky.ticket.util.AddrUtil;
import com.airnewslinkosky.ticket.util.Constants;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.mobclick.android.MobclickAgent;

/**
 * @author CX
 *
 */
public class OrderSearch extends BaseActivity {
	
	private final static int DATE_DIALOG = 0;
	private final static int TIME_DIALOG = 1;
	public final int NORESULT = 3;
	public final int NOORDER = 4;
	public final int NOORDERSTAT = 5;
	public final int NET_ERROR=6;
	public final int SEARCH_ERROR=7;
	public  final int TIME_DIALOG_ID = 8;
	public  final int DIALOG_SINGLE_CHOICE = 9;
	public  final int DIALOG_LIST = 10;
	
	private EditText orderNo, pnrNumber, flightTicketNo, passagerName, passagerPhone, passagerIDNo;
	private TextView orderTimeStart, orderTimeEnd, orderStatus, outTicketType, customerType;
	
	String[] selectOptionList=null;
	String[] selectOptionValueList=null;
	
	private Calendar c = null;
	
	private ProgressDialog progressDialog = null;
	
	
	private AddrUtil addrUtil;
	
	private FlyUtil flyUtil;
	
    private SharedPreferences sp;
	private String loginNameRe = "";
	private String isLoninOK = null;//是否登录
	private String autoLogin = null;//记着登录
	private ImageView backBut;
	private Toast toast;
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_search);
		
		activityList.add(this);  
		
		addrUtil = new AddrUtil(this);
		flyUtil = new FlyUtil(this);
		
		orderNo = (EditText)findViewById(R.id.orderNo);
		pnrNumber = (EditText)findViewById(R.id.pnrNumber);
		flightTicketNo = (EditText)findViewById(R.id.flightTicketNo);
		passagerName = (EditText)findViewById(R.id.passagerName);
		passagerPhone = (EditText)findViewById(R.id.passagerPhone);
		passagerIDNo = (EditText)findViewById(R.id.passagerIDNo);
		
		orderStatus = (TextView)findViewById(R.id.orderStatus);
		orderStatus.setOnClickListener(clickListener);
		orderTimeStart = (TextView)findViewById(R.id.orderTimeStart);
		orderTimeStart.setOnClickListener(clickListener);
		orderTimeEnd = (TextView)findViewById(R.id.orderTimeEnd);
		orderTimeEnd.setOnClickListener(clickListener);
		outTicketType = (TextView)findViewById(R.id.outTicketType);
		outTicketType.setOnClickListener(clickListener);
		customerType = (TextView)findViewById(R.id.customerType);
		customerType.setOnClickListener(clickListener);
		
		findViewById(R.id.orderSearchButton).setOnClickListener(clickListener);
		findViewById(R.id.clearAll).setOnClickListener(clickListener);
		findViewById(R.id.backBut).setOnClickListener(clickListener);
		findViewById(R.id.btn_single_search).setOnClickListener(clickListener);
		findViewById(R.id.btn_complex_search).setOnClickListener(clickListener);
		findViewById(R.id.btn_status_search).setOnClickListener(clickListener);
		
		sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
		initConfig();
	}
	
	OnClickListener clickListener= new OnClickListener() { 
    	public void onClick(View v) { 
    		switch (v.getId()) {
    		case R.id.btn_single_search: {//显示单一查询
    			findViewById(R.id.btn_single_search).setVisibility(View.GONE);
    			findViewById(R.id.btn_complex_search).setVisibility(View.VISIBLE);
    			findViewById(R.id.layout_single_search).setVisibility(View.VISIBLE);
    			findViewById(R.id.layout_complex_search).setVisibility(View.GONE);
    			break;
    		}
    		case R.id.btn_complex_search: {//显示复合查询
    			findViewById(R.id.btn_single_search).setVisibility(View.VISIBLE);
    			findViewById(R.id.btn_complex_search).setVisibility(View.GONE);
    			findViewById(R.id.layout_single_search).setVisibility(View.GONE);
    			findViewById(R.id.layout_complex_search).setVisibility(View.VISIBLE);
    			findViewById(R.id.outTicketTypeLayout).setVisibility(View.VISIBLE);
            	  findViewById(R.id.customerTypeLayout).setVisibility(View.VISIBLE);
    			break;
    		}
    		case R.id.btn_status_search: {
    			selectOptionList=new String[]{"等待支付的订单","等待出票的订单","等待退款的订单"};
  	          new AlertDialog.Builder(OrderSearch.this)
  	            .setTitle("根据订单状态查询")
  	            .setItems(
  	            		selectOptionList,
  	            		new DialogInterface.OnClickListener() {
  	    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
  	    	            	  findViewById(R.id.layout_single_search).setVisibility(View.GONE);
  	    	            	  findViewById(R.id.layout_complex_search).setVisibility(View.VISIBLE);
  	    	            	  findViewById(R.id.outTicketTypeLayout).setVisibility(View.GONE);
  	    	            	  findViewById(R.id.customerTypeLayout).setVisibility(View.GONE);
  	    	            	  switch(whichcountry) {
  	    	            	  case 0:{
  	    	            		orderStatus.setText(flyUtil.getOrderStatusNameByCode("00"));
  	    	            		orderStatus.setTag("00");
  	    	            		break;
  	    	            	  }
  	    	            	  case 1: {
  	    	            		orderStatus.setText(flyUtil.getOrderStatusNameByCode("01"));
  	    	            		orderStatus.setTag("01");
  	    	            		break;
  	    	            	  }
  	    	            	  case 2: {
  	    	            		orderStatus.setText(flyUtil.getOrderStatusNameByCode("05"));
  	    	            		orderStatus.setTag("05");
  	    	            		break;
  	    	            	  }
  	    	            	  default:
  	    	            		  break;
  	    	            	  }
  	    	              }
  	    	            })
  	            .setNegativeButton(
  	            		"取消", 
  	            		new DialogInterface.OnClickListener() { 
  	    	              public void onClick(DialogInterface d, int which) { 
  	    	                d.dismiss(); 
  	    	              }
  	    	            })
  	            .show();
    			break;
    		}
    		case R.id.orderStatus: {//订单状态
    			selectOptionList=new String[]{"全部订单","等待审核","等待订位","等待支付","支付成功","出票完成","申请废票","申请退票","退款成功","取消订单","审核失败","订位失败","订单关闭" };
    			selectOptionValueList =  new String[]{"","00","00","00","01","02","07","03","04","11","17","17","17" };
    			new AlertDialog.Builder(OrderSearch.this)
    	            .setTitle("选择")
    	            .setItems(
    	            		selectOptionList,
    	            		new DialogInterface.OnClickListener() {
    	    	              public void onClick(DialogInterface dialog, int which) {                                      
    	    	            	  orderStatus.setText(selectOptionList[which]);
    	    	            	  orderStatus.setTag(selectOptionValueList[which]);
    	    	              }
    	    	            })
    	            .setNegativeButton(
    	            		"取消", 
    	            		new DialogInterface.OnClickListener() { 
    	    	              public void onClick(DialogInterface d, int which) { 
    	    	                d.dismiss(); 
    	    	              }
    	    	            })
    	            .show();
    	          break;
    			}
    		case R.id.orderTimeStart: {//选择开始日期
    			showDialog(R.id.orderTimeStart);
    	        break;
    		}
    		case R.id.orderTimeEnd: {//选择结束日期
    			showDialog(R.id.orderTimeEnd);
    			break;
  			}
    		case R.id.outTicketType: {//出票状态
    			selectOptionList=new String[]{"全部订单","自动出票","手工出票","特殊政策"};
    	          new AlertDialog.Builder(OrderSearch.this)
    	            .setTitle("选择")
    	            .setItems(
    	            		selectOptionList,
    	            		new DialogInterface.OnClickListener() {
    	    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
    	    	            	  outTicketType.setText(selectOptionList[whichcountry]);
    	    	              }
    	    	            })
    	            .setNegativeButton(
    	            		"取消", 
    	            		new DialogInterface.OnClickListener() { 
    	    	              public void onClick(DialogInterface d, int which) { 
    	    	                d.dismiss(); 
    	    	              }
    	    	            })
    	            .show();
    	          break;
    			}
    		case R.id.customerType: {//客户类型
    			selectOptionList=new String[]{"全部订单"};
    	          new AlertDialog.Builder(OrderSearch.this)
    	            .setTitle("选择")
    	            .setItems(
    	            		selectOptionList,
    	            		new DialogInterface.OnClickListener() {
    	    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
    	    	            	  customerType.setText(selectOptionList[whichcountry]);
    	    	              }
    	    	            })
    	            .setNegativeButton(
    	            		"取消", 
    	            		new DialogInterface.OnClickListener() { 
    	    	              public void onClick(DialogInterface d, int which) { 
    	    	                d.dismiss(); 
    	    	              }
    	    	            })
    	            .show();
    	          break;
    			}
    		case R.id.orderSearchButton: {//订单查询
    			search();
    	        break;
    		}
    		case R.id.clearAll: {
    			orderNo.setText("");
    			pnrNumber.setText("");
    			flightTicketNo.setText("");
    			passagerName.setText("");
    			passagerPhone.setText("");
    			passagerIDNo.setText("");
    			orderTimeStart.setText("");
    			orderTimeEnd.setText("");
    			orderStatus.setText("");
    			outTicketType.setText("");
    			customerType.setText("");
    			break;
    		}
    		case R.id.backBut:
    			Intent intentR = new Intent();
    			intentR.setClass(OrderSearch.this, Main.class);
    			Bundle bundleR=new  Bundle();
    			bundleR.putString("loginNameB2B", loginNameRe);
    			bundleR.putString("isLoninOKB2B", isLoninOK);
    			bundleR.putString("autoLoginB2B", autoLogin);
    			sp.edit().putString("loginNameB2B",loginNameRe).commit();
    			sp.edit().putString("isLoninOKB2B",isLoninOK).commit();
    			sp.edit().putString("isAutoLoginB2B",autoLogin).commit();
    			intentR.putExtras(bundleR);
    			setResult(RESULT_OK, intentR);
    			finish();
				break;
    		}
    	}
	};
	
    //初始化配置
    private void initConfig() {
//     sp = getSharedPreferences("UserInfoB2B", 0);
//     loginNameRe = sp.getString("loginNameB2B", "");
//     isLoninOK = sp.getString("isLoninOKB2B", null);
//     autoLogin = sp.getString("isAutoLoginB2B", null);
    }
    
    public Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NORESULT:
				toast = Toast.makeText(OrderSearch.this, "未找到符合条件的航班", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case NOORDER:
				toast = Toast.makeText(OrderSearch.this, "无订单信息", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case NOORDERSTAT:
				toast = Toast.makeText(OrderSearch.this, "订单信息未获得更新", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case NET_ERROR:
				toast = Toast.makeText(OrderSearch.this, "网络超时，连接失败", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case SEARCH_ERROR:
				toast = Toast.makeText(OrderSearch.this, (String)msg.obj, Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			}
			super.handleMessage(msg);
		}
	};
    
	/**
     * 创建日期选择对话框
     */
    @Override
	protected Dialog onCreateDialog(final int id) {
		Dialog dialog = null;
		c = Calendar.getInstance();
		dialog = new DatePickerDialog(this,
				new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker dp, int year, int month,
							int dayOfMonth) {
						if (R.id.orderTimeStart == id) {
							orderTimeStart.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
						} else if (R.id.orderTimeEnd == id) {
							orderTimeEnd.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
						}
					}
				}, c.get(Calendar.YEAR), // 传入年份
				c.get(Calendar.MONTH), // 传入月份
				c.get(Calendar.DAY_OF_MONTH) // 传入天数
		);

		return dialog;
	}	
    
    private void search() {
    	final String ticketNoValue = "";
    	final String orderNoValue = orderNo.getText().toString();
    	final String pnrNumberValue = pnrNumber.getText().toString();
    	final String flightTicketNoValue = flightTicketNo.getText().toString();
    	final String passagerNameValue = passagerName.getText().toString();
    	final String passagerPhoneValue = passagerPhone.getText().toString();
    	final String passagerIDNoValue = passagerIDNo.getText().toString();
    	
    	final String orderTimeStartValue = orderTimeStart.getText().toString();
    	final String orderTimeEndValue = orderTimeEnd.getText().toString();
    	final String orderStatusValue = orderStatus.getTag() != null ? orderStatus.getTag().toString() : "";
    	final String outTicketTypeValue = outTicketType.getText().toString();
    	final String customerTypeValue = customerType.getText().toString();
		
		ContentValues values = new ContentValues();
		values.put("OrderNo", orderNoValue);
		values.put("PNR", pnrNumberValue);
		values.put("TicketNo", flightTicketNoValue);
		values.put("OrderStatus", orderStatusValue);
		values.put("PassagerName", passagerNameValue);
		values.put("OrderTimeStart", orderTimeStartValue);
		values.put("orderTimeEnd", orderTimeEndValue);
		values.put("ticketNo", ticketNoValue);
		//HistoryDB.insert(OrderSearch.this, values);
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询订单中...",true);
		final Thread thread1 = new Thread() {
			public void run() {
				SearchOrder searchOrder = new SearchOrder();
				searchOrder.OrderNo = orderNoValue;
				searchOrder.PNR = pnrNumberValue;
				searchOrder.TicketNo = ticketNoValue;
				searchOrder.OrderStatus = orderStatusValue;
				searchOrder.PassagerName = passagerNameValue;
				searchOrder.StartOrderTime = orderTimeStartValue;
				searchOrder.EndOrderTime = orderTimeEndValue;
				
//				sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
//		        String userIdLogin = sp.getString("userIdB2B", null);
//		        Log.i("OrderSearch userIdLogin", userIdLogin);
//		        String userPwd =  sp.getString("userPwdB2B", null);
//		        Log.i("OrderSearch userPwd", userPwd);
		        
		        String userIdLogin = Constants.USERID;
		        String userPwd =  Constants.USERPWD;
		        String asToken =  Constants.ASToken;
		        
				OrderInfoResult orderInfoResult =  WebAccessor.searchOrderInfo(OrderSearch.this, searchOrder,userIdLogin,userPwd);
				
				if (progressDialog.isShowing()) {
					if (orderInfoResult== null) {
						Message msg = new Message();
						msg.what = NORESULT;
						myHandler.sendMessage(msg);
					}else if(!"0".equals(orderInfoResult.Ret_Code)){
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = orderInfoResult.Ret_Msg;
						myHandler.sendMessage(msg);
					}else{
						Intent intent3 = new Intent();
						intent3.setClass(OrderSearch.this, OrderList.class);
						intent3.putExtra("searchOrder", searchOrder);
						intent3.putExtra("orderStatus",orderStatusValue);
						intent3.putExtra("orderTimeEnd", orderTimeEndValue);
						OrderList.orderist = orderInfoResult.OrderInfos;
						OrderList.searchOrder = searchOrder;
						Log.i("OrderList", String.valueOf(orderInfoResult.OrderInfos.size()));
						startActivity(intent3);
						overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread1.start();
	}
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
